<!doctype html>
<!--
Copyright 2018 The Immersive Web Community Group

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<html>
  <head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'>
    <meta name='mobile-web-app-capable' content='yes'>
    <meta name='apple-mobile-web-app-capable' content='yes'>

    <!-- Origin Trial Token, feature = WebXR Device API (For Chrome M76+), origin = storage.googleapis.com, expires = 2019-07-24 -->
    <meta http-equiv="origin-trial" data-feature="WebXR Device API (For Chrome M76+)" data-expires="2019-07-24" content="Ap6io/uhkGK7vXCD+golNnQfj8wJ4so790EzZoqb8YOljMXIBTvBEQFPTHYIz5d/BgtuwZTKOLrmHAOt30f38g8AAABxeyJvcmlnaW4iOiJodHRwczovL3N0b3JhZ2UuZ29vZ2xlYXBpcy5jb206NDQzIiwiZmVhdHVyZSI6IldlYlhSRGV2aWNlTTc2IiwiZXhwaXJ5IjoxNTY0MDA5MzU2LCJpc1N1YmRvbWFpbiI6dHJ1ZX0=">

    <title>Magic Window</title>

    <link href='css/common.css' rel='stylesheet'></link>

    <!--The polyfill is not needed for browser that have native API support,
        but is linked by these samples for wider compatibility.-->
    <!--script src='https://cdn.jsdelivr.net/npm/webxr-polyfill@latest/build/webxr-polyfill.js'></script-->
    <script src='js/xrray-polyfill.js' type='module'></script>
    <script src='js/webxr-polyfill.js'></script>

    <script src='js/webxr-button.js'></script>
    <script>
      var inlineSession = null
      function updateFOV() {
        var fov = document.getElementById("vertFOV").value;
        if (inlineSession) {
          inlineSession.updateRenderState({
            inlineVerticalFieldOfView: fov
          });
        }
      }
    </script>
  </head>
  <body>
    <header>
      <details open>
        <summary>Magic Window</summary>
        <p>
          This sample demonstrates use of a non-immersive XRSession to present
          'Magic Window' content prior to entering XR presentation with an
          immersive session. The viewer pose can be adjusted by clicking and
          dragging with mouse or touch.
        </p>
        <p>
          <a class="back" href="./index.html">Back</a>
        </p>
        <p>
          You can also modify the vertical FOV.  The browser will clamp
          the value between 0.01 and 3.13 inclusive.
        </p>
        <p>
          <!-- Note: Not clamping the input box so we can validate 'bad' values -->
          <label for="vertFOV">Vertical FOV (Radians): </label>
          <input id="vertFOV" type="number" value="1.57">
          <button onclick="updateFOV()">Update</button>
        </p>
      </details>
    </header>
    <script type="module">
      import {Scene} from './js/cottontail/src/scenes/scene.js';
      import {Renderer, createWebGLContext} from './js/cottontail/src/core/renderer.js';
      import {Gltf2Node} from './js/cottontail/src/nodes/gltf2.js';
      import {QueryArgs} from './js/cottontail/src/util/query-args.js';
      import {SkyboxNode} from './js/cottontail/src/nodes/skybox.js';
      import {mat4, vec3, quat} from './js/cottontail/src/math/gl-matrix.js';

      // If requested, initialize the WebXR polyfill
      if (QueryArgs.getBool('allowPolyfill', false)) {
        var polyfill = new WebXRPolyfill();
      }

      // Shh! Nothing to see here, move along.
      let arMode = QueryArgs.getBool('arMode', false);

      // XR globals.
      let xrButton = null;
      let xrRefSpaces = {};

      // WebGL scene globals.
      let gl = null;
      let renderer = null;
      let scene = new Scene();
      let solarSystem = new Gltf2Node({url: '../media/gltf/space/space.gltf'});
      scene.addNode(solarSystem);

      if (arMode) {
        solarSystem.scale = [0.2, 0.2, 0.2];
      } else {
        scene.addNode(new SkyboxNode({url: '../media/textures/milky-way-4k.png'}));
      }

      function initXR() {
        xrButton = new XRDeviceButton({
          onRequestSession: requestImmersiveSession,
          onEndSession: session => session.end(),
          supportedSessionTypes: ['immersive-vr']
        });
        xrButton.addToHeader();

        // Pick an arbitrary device for the magic window content and start
        // up a non-immersive non-local session.
        requestInlineSession()
        .then(session => {
          // Once the initial inline session has been set up, create a session
          // supporting the local reference space when we have user activation.
          gl.canvas.addEventListener('touchend', () => {
            session.end().then(() => requestInlineSession({optionalFeatures: ['local']}))
          }, { once: true });
        });
      }

      function requestSession(mode, options) {
        if (navigator.xr) {
          return navigator.xr.requestSession(mode, options).then(session => {
            session.mode = mode;
            return session;
          });
        } else {
          return Promise.reject();
        }
      }

      function requestImmersiveSession(options) {
        return requestSession('immersive-vr', options).then(session => {
          xrButton.setSession(session);
          session.addEventListener('end', () => xrButton.setSession(null));

          return onSessionStarted(session);
        });
      }

      function requestInlineSession(options) {
        return requestSession('inline', options).then(session => {
          console.assert(inlineSession === null);
          inlineSession = session;
          session.addEventListener('end', () => inlineSession = null);
          updateFOV();

          return onSessionStarted(session);
        });
      }

      function onSessionStarted(session) {
        if (!gl) {
          gl = createWebGLContext({
            xrCompatible: true
          });
          document.body.appendChild(gl.canvas);

          function onResize () {
            gl.canvas.width = (gl.canvas.offsetWidth * window.devicePixelRatio);
            gl.canvas.height = (gl.canvas.offsetHeight * window.devicePixelRatio);
          }
          window.addEventListener('resize', onResize);
          onResize();

          renderer = new Renderer(gl);

          scene.setRenderer(renderer);

          // Make the canvas listen for touch events so that we can adjust the
          // viewer pose accordingly in inline sessions.
          gl.canvas.addEventListener("touchstart", onTouchStart);
          gl.canvas.addEventListener("touchend", onTouchEnd);
          gl.canvas.addEventListener("touchcancel", onTouchCancel);
          gl.canvas.addEventListener("touchmove", onTouchMove);
        }

        session.updateRenderState({
          baseLayer: new XRWebGLLayer(session, gl)
        });

        // Try to get a local reference space, if possible
        session.requestReferenceSpace('local')
        .catch(e => {
          if (session.mode === 'inline') {
            // We can accept failure to get local reference space for inline sessions.
            // Our underlying platform may not support local reference spaces, but a viewer space is guaranteed.
            return session.requestReferenceSpace('viewer');
          } else {
            throw e;
          }
        }).then(refSpace => {
          // Since we're dealing with multple sessions now we need to track
          // which XRReferenceSpace is associated with which XRSession.
          console.assert(!xrRefSpaces[session.mode]);
          xrRefSpaces[session.mode] = refSpace;
          session.addEventListener('end', () => xrRefSpaces[session.mode] = null);

          session.requestAnimationFrame(onXRFrame);
        });

        return session;
      }

      // Allow the user to click and drag the mouse (or touch and drag the
      // screen on handheld devices) to adjust the viewer pose for inline
      // sessions.
      let lookYaw = 0;
      let lookPitch = 0;
      const lookSpeed = 0.0025;

      function processMoveEvent(dx, dy) {
        lookYaw += dx * lookSpeed;
        lookPitch += dy * lookSpeed;
        if (lookPitch < -Math.PI*0.5)
            lookPitch = -Math.PI*0.5;
        if (lookPitch > Math.PI*0.5)
            lookPitch = Math.PI*0.5;
      }


      window.addEventListener('mousemove', (ev) => {
        // Only rotate when the left button is pressed
        if (ev.buttons && 1) {
          processMoveEvent(ev.movementX, ev.movementY);
        }
      });

      // Keep track of touch-related state so that users can touch and drag on
      // the canvas to adjust the viewer pose in an inline session.
      let primaryTouch = undefined;
      let prevTouchX = undefined;
      let prevTouchY = undefined;
      let currentTouches = new Set();

      // Keep track of all active touches, but only use the first touch to
      // adjust the viewer pose.
      function onTouchStart(event) {
        let touches = event.changedTouches;
        for (let i = 0; i < touches.length; ++i) {
          let touch = touches[i];
          let id = touch.identifier;
          if (primaryTouch == undefined) {
            primaryTouch = id;
            prevTouchX = touch.pageX;
            prevTouchY = touch.pageY;
          }
          currentTouches.add(id);
        }
      }

      // Update the set of active touches now that one or more touches finished.
      // If the primary touch just finished, update the viewer pose based on the
      // final touch movement.
      function onTouchEnd(event) {
        let touches = event.changedTouches;
        for (let i = 0; i < touches.length; ++i) {
          let touch = touches[i];
          let id = touch.identifier;
          if (id == primaryTouch) {
            let dx = touch.pageX - prevTouchX;
            let dy = touch.pageY - prevTouchY;
            processMoveEvent(dx, dy);
            primaryTouch = undefined;
          }
          currentTouches.delete(id);
        }
      }

      // Update the set of active touches now that one or more touches was
      // cancelled. Don't update the viewer pose when the primary touch was
      // cancelled.
      function onTouchCancel(event) {
        let touches = event.changedTouches;
        for (let i = 0; i < touches.length; ++i) {
          let touch = touches[i];
          let id = touch.identifier;
          if (id == primaryTouch) {
            primaryTouch = undefined;
          }
          currentTouches.delete(id);
        }
      }

      // Only use the delta between the most recent and previous events for the
      // primary touch. Ignore the other touches.
      function onTouchMove(event) {
        let touches = event.changedTouches;
        for (let i = 0; i < touches.length; ++i) {
          let touch = touches[i];
          let id = touch.identifier;
          if (id == primaryTouch) {
            let dx = touch.pageX - prevTouchX;
            let dy = touch.pageY - prevTouchY;
            processMoveEvent(dx, dy);
            prevTouchX = touch.pageX;
            prevTouchY = touch.pageY;
          }
        }
      }

      // XRReferenceSpace offset is immutable, so return a new reference space
      // that has an updated orientation.
      function getAdjustedRefSpace(refSpace) {
        // Represent the rotational component of the reference space as a
        // quaternion.
        let invOrientation = quat.create();
        quat.rotateX(invOrientation, invOrientation, -lookPitch);
        quat.rotateY(invOrientation, invOrientation, -lookYaw);
        let xform = new XRRigidTransform(
            {x: 0, y: 0, z: 0},
            {x: invOrientation[0], y: invOrientation[1], z: invOrientation[2], w: invOrientation[3]});
        return refSpace.getOffsetReferenceSpace(xform);
      }

      // Called every time a XRSession requests that a new frame be drawn.
      function onXRFrame(t, frame) {
        let session = frame.session;

        // Per-frame scene setup. Nothing WebXR specific here.
        scene.startFrame();

        // Inform the session that we're ready for the next frame.
        session.requestAnimationFrame(onXRFrame);

        // Ensure that we're using the right reference space for the session.
        let refSpace = xrRefSpaces[session.mode];

        // Account for the click-and-drag mouse movement or touch movement when
        // calculating the viewer pose for inline sessions.
        if (session.mode == 'inline') {
          refSpace = getAdjustedRefSpace(refSpace);
        }

        let pose = frame.getViewerPose(refSpace);

        // In most other samples, these rendering details will be handeld by
        // cottontail by calling scene.drawXRFrame.
        if (pose) {
          gl.bindFramebuffer(gl.FRAMEBUFFER, session.renderState.baseLayer.framebuffer);
          if (!arMode) {
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
          }

          // Loop through each of the views reported by the frame and draw them
          // into the corresponding viewport.
          for (let view of pose.views) {
            let viewport = session.renderState.baseLayer.getViewport(view);
            gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);

            // Draw this view of the scene. What happens in this function really
            // isn't all that important. What is important is that it renders
            // into the XRWebGLLayer's framebuffer, using the viewport into that
            // framebuffer reported by the current view, and using the
            // projection and view matricies from the current view and pose.
            // We bound the framebuffer and viewport up above, and are passing
            // in the appropriate matrices here to be used when rendering.
            scene.draw(view.projectionMatrix, view.transform.inverse.matrix);
          }
        } else {
          // There's several options for handling cases where no pose is given.
          // The simplest, which these samples opt for, is to simply not draw
          // anything. That way the device will continue to show the last frame
          // drawn, possibly even with reprojection. Alternately you could
          // re-draw the scene again with the last known good pose (which is now
          // likely to be wrong), clear to black, or draw a head-locked message
          // for the user indicating that they should try to get back to an area
          // with better tracking. In all cases it's possible that the device
          // may override what is drawn here to show the user it's own error
          // message, so it should not be anything critical to the application's
          // use.
        }

        // Per-frame scene teardown. Nothing WebXR specific here.
        scene.endFrame();
      }

      // Start the XR application.
      initXR();
    </script>
  </body>
</html>
